package com.baizhi.controller;

import com.baizhi.entity.CmfzBanner;
import com.baizhi.service.CmfzBannerService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("banner")
public class CmfzBannerController {
    @Autowired
    @Resource
    private CmfzBannerService cbs;
    @RequestMapping("allBanner")
    public Map allBanner(@RequestParam(defaultValue = "1",value = "page") int pageNo, @RequestParam(defaultValue = "4",value = "limit") int pageSize){
        Map<String, Object> map = cbs.bannerListByPage(pageNo, pageSize);


        return map;
    }




    //添加一个轮播图
    @RequestMapping("addBanner")
    public Boolean addBanner(CmfzBanner banner){
        try {
            cbs.insert(banner);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        }
    }

    //假删除一个轮播图,下架
    @RequestMapping("delBanner")
    public Boolean delBanner(int id){
        try {
            cbs.delete(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //上传
    @RequestMapping("upload")
    public Map upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //在文件名的前面添加上uuid避免文件名被覆盖
        String newName= UUID.randomUUID().toString()+ file.getOriginalFilename();

        //把文件复制到这个目录里面。
        file.transferTo(new File("D:/img/"+newName));

        //响应信息。code=0表示上传成功，src是图片上传后新的名字
        Map map=new HashMap();
        map.put("code",0);
        map.put("src",newName);
        return map;
    }

}
